import BaseButton from '@/components/base/BaseButton';
import BaseForm, {
  BaseFormSelect,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect
} from '@/components/base/BaseForm';
import BaseModal, { ModalFC } from '@/components/base/BaseModal';
import BaseUpload from '@/components/base/BaseUpload';
import useUserStore from '@/store/user';
import { download } from '@/utils';
import { isEmpty } from '@/utils/is';
import { useRequest } from '@/utils/request';
import { DownloadOutlined } from '@ant-design/icons';
import { Alert, Form, Progress } from 'antd';
import { useRef, useState } from 'react';
import { getClassList } from '../../ClassInfo/api';
import { StudentModel } from '../../data';
import { getMajorList } from '../../MajorInfo/api';
import { getImportStatus } from '../api';

const ImportModal: ModalFC = (props) => {
  const { onSuccess, onCancel, ...rest } = props;
  const formRef = useRef<ProFormInstance<StudentModel>>();
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [importStatus, setImportStatus] = useState<string>('loading');

  const loadStatus = useRequest(getImportStatus, {
    pollingInterval: 5000,
    manual: true,
    onSuccess(data) {
      if (data === 100) {
        setImportStatus('success');
      }
    },
    onError() {
      setImportStatus('fail');
      loadStatus.cancel();
    }
  });
  const {
    userinfo: { area }
  } = useUserStore();
  return (
    <BaseModal title='学生信息导入' footer={false} onCancel={onCancel} {...rest}>
      {uploadSuccess ? (
        <div>
          {importStatus === 'loading' && (
            <Progress
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068'
              }}
              percent={loadStatus.data}
            />
          )}
          {importStatus === 'success' && (
            <Alert style={{ textAlign: 'center' }} message='学生信息导入成功' type='success' />
          )}
          {importStatus === 'error' && (
            <Alert style={{ textAlign: 'center' }} message='学生信息导入失败' type='error' />
          )}
          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}>
            <BaseButton
              type='primary'
              disabled={importStatus === 'loading'}
              onClick={() => {
                if (importStatus === 'success') {
                  onSuccess && onSuccess();
                  onCancel && onCancel();
                }
              }}
            >
              确定
            </BaseButton>
          </div>
        </div>
      ) : (
        <BaseForm labelCol={{ style: { width: 70 } }} formRef={formRef} layout='horizontal'>
          <Form.Item label='学生模板'>
            <BaseButton
              type='primary'
              onClick={() => {
                download(`${window.origin}/template/studentImportTemplate.xlsx`, {
                  filename: '学生信息导入模板'
                });
              }}
              icon={<DownloadOutlined />}
            >
              导入模板下载
            </BaseButton>
          </Form.Item>
          <BaseFormSelect
            request={getMajorList}
            label='专业'
            placeholder='请选择学生专业'
            name='majorId'
            fieldProps={{
              fieldNames: { label: 'majorName', value: 'id' },
              onChange: () => {
                formRef.current?.setFieldsValue({ classId: undefined });
              }
            }}
            rules={[{ required: true, message: '请选择学生专业' }]}
          />
          <ProFormDependency name={['majorId']}>
            {({ majorId }) => (
              <BaseFormSelect
                label='班级'
                name='classId'
                request={getClassList}
                placeholder='请选择学生班级'
                rules={[{ required: true, message: '请选择学生班级' }]}
                hiddenItem={isEmpty(majorId)}
                hiddenRender={() => <Alert message='请先选择专业' type='warning' />}
                fieldProps={{
                  params: { majorId },
                  fieldNames: { label: 'className', value: 'id' }
                }}
              />
            )}
          </ProFormDependency>
          <ProFormSelect
            label='服务区域'
            name='areaId'
            placeholder='请选择服务区域'
            rules={[{ required: true, message: '请选择服务区域' }]}
            fieldProps={{ mode: 'multiple' }}
            options={area.map((i) => ({ label: i.areaName, value: i.areaId }))}
          />
          <ProFormDependency name={['classId', 'areaId']}>
            {({ classId, areaId = [] }) => {
              const titles = [];
              if (isEmpty(classId)) {
                titles.push('班级');
              }
              if (isEmpty(areaId)) {
                titles.push('服务区域');
              }
              const disabled = titles.length > 0;
              return (
                <BaseUpload.Dragger
                  accept='.xlsx,.xls'
                  data={{ classId, areaIds: areaId.join(',') }}
                  disabled={disabled}
                  onChange={() => {
                    setUploadSuccess(true);
                    loadStatus.run();
                  }}
                  action='/pc/user/v1/importStudent'
                  title='学生Execl上传'
                  desc={
                    disabled
                      ? `请先选择学生${titles.join('、')}`
                      : '只能上传xlsx、xls文件，文件应小于100M'
                  }
                />
              );
            }}
          </ProFormDependency>
        </BaseForm>
      )}
    </BaseModal>
  );
};

export default ImportModal;
